﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

public class LSystemManager
{
    [Serializable]
    public struct Grammar
    {
        public char src;
        public string tar;
    }

    private Dictionary<char,List<string>> map;

    public LSystemManager()
    {
        map = new Dictionary<char, List<string>>();
    }
    
    public void AddGrammar(string grammar)
    {
        if (grammar.Equals("")) return;
        grammar = Regex.Replace(grammar, @"\s", "");
        string[] strings = Regex.Split(grammar,":");
       
        // 如果src部分大于一个字符抛出异常
        if (strings[0].Length > 1) {
            throw new Exception("文法错误!");
        }
        
        Grammar result = new Grammar
        {
            src = strings[0].ToArray()[0],
            tar = strings[strings.Length - 1]
        };
        if (map.ContainsKey(result.src)) {
            map[result.src].Add(result.tar);
        }
        else {
            map.Add(result.src,new List<string>());
            map[result.src].Add(result.tar);
        }
    }
    
    public string GenerateSentence(string axiom,int step,ref int num)
    {
        string sentence = axiom;
        string nextSentence = "";

        int iter = step;
        while (iter > 0)
        {
            for (int i = 0; i < sentence.Length; i++)
            {
                bool found = false;
                char current = sentence[i];

                foreach (char key in map.Keys) {
                    if (current == key) {
                        found = true;
                        nextSentence += map[key][0];
                        break;
                    }
                }
                // 当前字符没有匹配到文法规则不进行替换，原样添加到新文法序列中
                if (!found)
                {
                    nextSentence += current;
                }
            }
            // 更新当前文法序列
            sentence = nextSentence;
            nextSentence = "";
            iter--;
        }

        for (int i = 0; i < sentence.Length; i++) {
            if (sentence[i] == 'F') {
                num++;
            }
        }
        
        return sentence;
    }
    
    

    // private static Grammar[] grammars =
    // {
    //     new Grammar()
    //     {
    //         src = 'X',
    //         tar = "F[/+XC][*&X&FC][/-XC][*^XC]"
    //     },
    //     new Grammar()
    //     {
    //     src = 'F',
    //     tar = "F"
    //     },
    //     new Grammar()
    //     {
    //     src = 'X',
    //     tar = "F[+*X][-^X][+&X][--**X]"
    //     }
    //
    // };
}